package edu.uestc.fly.performancetest.cpu;

import android.os.AsyncTask;

import edu.uestc.fly.performancetest.constant.Constant;
import edu.uestc.fly.performancetest.utils.ProgressListen;

/**
 * Created by flyln on 2017/10/23 15:42.
 * email:xyf_uestc@163.com
 *
 * String*********对应我们的URL类型
 * Integer********进度条的进度值
 * BitMap*********异步任务完成后返回的类型
 *
 */
public class CPUAsyncTask extends AsyncTask<String, Integer, Double> {

    public ProgressListen progresslistener;
    public Constant.TaskType taskType = Constant.TaskType.CPU;

    //执行异步任务（doInBackground）之前执行，并且在ui线程中执行
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();


        if (progresslistener != null){
            progresslistener.initProgress(taskType,0);
        }


    }

    @Override
    protected Double doInBackground(String... params) {
        // TODO Auto-generated method stub
        //params是一个可变长的数组 在这里我们只传进来了一个url

        int total = Constant.COUNT_PRIME;
        int max = Constant.MAX_PRIME;
        //查找开始时间
        long StartTime=System.currentTimeMillis();
        long EndTime = 0;

        int number=0;

        for(int n=2;n<=max;n++) {
            int i=2;
            int m=(int)(Math.sqrt(n));
            for(;i<=m;i++) {
                if(n%i==0) {
                    break;
                }
            }
            if(i>m) {
                System.out.print(n+" ");
                number++;
                publishProgress((int)((float)number/(float) total*100));


            }
        }

        //查找结束时间
        EndTime = System.currentTimeMillis();
        System.out.println("\n素数有"+number+"个");
        System.out.println("查找时间："+(EndTime-StartTime)+"ms");


        return (double)EndTime - StartTime;
    }
    //在ui线程中执行 可以操作ui
    @Override
    protected void onPostExecute(Double runTime) {
        // TODO Auto-generated method stub
        super.onPostExecute(runTime);
        //任务完成，对话框进度条隐藏

        if (progresslistener != null){
            progresslistener.closeProgress(taskType,runTime);
        }
    }
    /*
     * 在doInBackground方法中已经调用publishProgress方法 更新任务的执行进度后
     * 调用这个方法 实现进度条的更新
     * */
    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
        if (progresslistener != null){
            progresslistener.updateProgress(taskType,values[0]);
        }
    }
}